<template>
  <div class="execution">
        <basic-container>
            <style-page
                :showTabsRight='false'
                :showTabsHeard='true'
            >
                <template slot="buttons">
                    <el-button @click='handerAsync' type="primary">保存</el-button>
                </template>

                <template slot="tabs">
                    <el-card class="box-card">
                        <div slot="header" class="clearfix">
                            <span>基本信息</span>
                        </div>
                        <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
                            <div class="formitem">
                                <div v-for="(item) in mapList" :key="item.props" :class="item.className">
                                    <aside v-text="item.title"></aside>
                                    <el-form-item style="width:80%" :prop="item.props">
                                        <el-input v-model="ruleForm[item.props]"></el-input>
                                    </el-form-item>
                                </div>

                                <div class="itembox">
                                    <aside>产品分类</aside>
                                    <el-form-item style="width:80%" prop="proType">
                                        <el-select v-model="ruleForm.proType">
                                            <el-option label="试用版" :value='0'>试用版</el-option>
                                            <el-option label="标准版" :value='1'>标准版</el-option>
                                        </el-select>
                                    </el-form-item>
                                </div>
                                <div class="itembox">
                                    <aside>部署方式</aside>     
                                    <el-form-item style="width:80%" prop="deployType">
                                        <el-select v-model="ruleForm.deployType">
                                            <el-option label="SAAS" value="1">SAAS</el-option>
                                            <el-option label="本地部署" value="2">本地部署</el-option>
                                        </el-select>
                                    </el-form-item>
                                </div>
                                <div class="itembottombox">
                                    <aside>备注类字段：</aside>
                                    <el-form-item style="width:100%" prop="proDesc">
                                        <el-input v-model="ruleForm.proDesc"></el-input>
                                    </el-form-item>
                                </div>
                            </div>
                        </el-form>
                    </el-card>
                    <el-card class="box-card">
                        <div slot="header" class="clearfix">
                            <span>其他信息</span>
                        </div>
                        <div>
                            <el-button @click="addProductClick" type="primary">新增</el-button>
                        </div>
                        <!-- 表格 -->
                        <el-table
                            v-loading="loading"
                            :data="menuList"
                            row-key="id"
                            :tree-props="{children: 'children', hasChildren: 'hasChildrens'}">
                            <el-table-column prop="name" label="菜单名称" :show-overflow-tooltip="true" width="180"></el-table-column>
                            <el-table-column prop="icon" label="图标" align="center" width="100">
                            <template slot-scope="scope">
                                <i :class="scope.row.icon"/>
                            </template>
                            </el-table-column>
                            <el-table-column prop="sort" label="排序" width="60"></el-table-column>
                            <el-table-column prop="path" label="组件路径" :show-overflow-tooltip="true"></el-table-column>
                            <el-table-column prop="type" label="类型" width="80" align="center">
                            <template slot-scope="scope">
                                <el-tag type="success" v-if="scope.row.type === '0'">菜单</el-tag>
                                <el-tag type="info" v-if="scope.row.type === '1'">按钮</el-tag>
                            </template>
                            </el-table-column>
                            <el-table-column prop="keepAlive" label="缓冲" width="80" align="center">
                            <template slot-scope="scope">
                                <el-tag type="info" v-if="scope.row.keepAlive === '0'">关闭</el-tag>
                                <el-tag type="success" v-if="scope.row.keepAlive === '1'">开启</el-tag>
                            </template>
                            </el-table-column>
                            <el-table-column prop="permission" label="权限标识" :show-overflow-tooltip="true"></el-table-column>

                            <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                            <template slot-scope="scope">
                                <el-button
                                size="small"
                                type="text"
                                icon="el-icon-delete"
                                @click="handleDelete(scope.row)">删除
                                </el-button>
                            </template>
                            </el-table-column> -->

                        </el-table>
                    </el-card>
                </template>
            </style-page>

            <el-dialog
                title="请选择商品"
                :visible.sync="centerDialogVisible"
                width="40%"
                center>
                <div class="dialog-main-tree" v-loading="loading">
                    <el-tree
                    ref="menuTree"
                    :data="treeData"
                    :default-checked-keys="checkedKeys"
                    :check-strictly="false"
                    :props="defaultProps"
                    :filter-node-method="filterNode"
                    @check='treeCheck'
                    @check-change='treeCheckChange'
                    class="filter-tree"
                    node-key="id"
                    highlight-current
                    show-checkbox/>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="centerDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="handerAdd">确 定</el-button>
                </span>
            </el-dialog>
        </basic-container>
    </div>
</template>

<script>
import {fetchProductMenuTree,fetchProductoms} from './api'
export default {
    data(){
        return{
            mapList:[
                {title:'商品许可编号', className:'itembox', props:'proSn'},
                {title:'商品名称', className:'itembox', props:'proName'},
                {title:'标准单价（元）', className:'itembox', props:'normalAmount'},
                {title:'预算金额：', className:'itembox', props:'budgetAmount'},
                {title:'销售单价（元）', className:'itembox', props:'saleAmount'},
                {title:'单位成本（元）', className:'itembox', props:' unitAmount'},
                {title:'子产品数量（套）', className:'itembox', props:'subNum'},
                {title:'使用人数限制（人）', className:'itembox', props:'limitNum'},
            ],
            ruleForm: {
                proSn:'',
                proName: '',
                normalAmount: '',
                budgetAmount: '',
                saleAmount: '',
                unitAmount: '',
                subNum:'',
                limitNum:'',
                proType:1,
                deployType:'1',
                proDesc: ''
            },
            rules: {
                name: [
                    { required: true, message: '请输入活动名称', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                normalAmount: [
                    { required: true, message: '请选择活动区域', trigger: 'change' }
                ],
                budgetAmount: [
                    { required: true, message: '请选择日期', trigger: 'change' }
                ],
                saleAmount: [
                    { required: true, message: '请选择时间', trigger: 'change' }
                ],
                unitAmount: [
                    { required: true, message: '请选择时间', trigger: 'change' }
                ],
                type: [
                    { type: 'array', required: true, message: '请至少选择一个活动性质', trigger: 'change' }
                ],
                resource: [
                    { required: true, message: '请选择活动资源', trigger: 'change' }
                ],
                proDesc: [
                    { required: true, message: '请填写活动形式', trigger: 'blur' }
                ]
            },
            // 表格数据
            menuList:[],
            loading: false,
            centerDialogVisible:false,
            // 弹框数据
            treeData: [],
            defaultProps: {
                label: 'name',
                value: 'id'
            },
            selectData:[],
            checkedKeys:[],
            halfCheckedKeys:[],
            // 发送给后端的id
            fetchAllId:[],

            dialogloading:false,
        }
    },
    components:{
    },
    created(){
        
    },
    methods:{
        listToTree (list) {
            const info = list.reduce((map, node) => (map[node.key] = node, node.fdChildren = [], map), {})
            return list.filter(node => {
                info[node.parentId] && info[node.parentId].fdChildren.push(node)
                return !node.parentId
            })
        },

        treeToList (tree) {
            const result = tree.map(node => (node.level = 1, node))
            for (let i = 0; i < result.length; i++) {
                if (!result[i].fdChildren) continue
                const list = result[i].fdChildren.map(node => (node.level = result[i].level + 1, node))
                result.splice(i + 1, 0, ...list)
            }
            return result
        },

        findNodeDate(allData,checkedKeys,halfCheckedKeys){
            let arr = []
            allData.map( (ele,idx) => {
                // 判断有子级
                if(ele.children && ele.children.length != 0){
                    // 当前节点为半选状态
                    if(halfCheckedKeys.indexOf(ele.id) > -1){
                        arr.push(ele)
                        ele.children = this.findNodeDate(ele.children,checkedKeys,halfCheckedKeys)
                    }   //当前节点为全选状态
                    else if(checkedKeys.indexOf(ele.id) > -1){
                        arr.push(ele)
                    }   //当前节点没有选择
                }else{  
                    //当前节点为全选状态
                    if(checkedKeys.indexOf(ele.id) > -1){
                        arr.push(ele)
                    }   //当前节点没有选择
                }
            })
            return arr
        },

        handerAsync(){
            this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
            })
            let newObj = {}
            Object.assign(newObj,{menuIds:this.fetchAllId},this.ruleForm);
            fetchProductoms(newObj).then(res => {
                if(res.data.code === 0){
                    console.log('ok');
                }
                this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                }).close()
                this.$router.push({name:'productoms'})
            })
        },
        addProductClick(){
            this.getList()
            this.dialogloading = true
            this.centerDialogVisible = true
        },
        treeCheck(targer,select){
            console.log(targer,select);
            // this.menuList = select.halfCheckedNodes
            this.fetchAllId = [...select.checkedKeys,...select.halfCheckedKeys]

            this.halfCheckedKeys = select.halfCheckedKeys
            this.checkedKeys = select.checkedKeys

            this.selectData = select.checkedNodes
        },
        treeCheckChange(targer,select,selectList){
            console.log(targer,select,selectList);
        },
        handerAdd(){
            console.log(this.selectData);
            // let arr = []
            // this.selectData.map(e => {
            //     if(e.children && e.children.length === 0){
            //         arr.push(e)
            //     }
            // })
            // this.checkedKeys = arr.map( e => e.id)
            // 处理表格数据
            this.menuList = this.findNodeDate(this.treeData,this.checkedKeys,this.halfCheckedKeys)
            console.log(this.menuList);

            this.centerDialogVisible = false
        },
        filterNode(value, data) {
            if (!value) return true
            return data.label.indexOf(value) !== -1
        },
        getList() {
            this.loading = true
            fetchProductMenuTree(false).then(response => {
                this.treeData = response.data.data
                this.dialogloading = false
                this.loading = false
            })
        },
        handleDelete(row){
            console.log("🚀 ~ file: index.vue ~ line 214 ~ handleDelete ~ row", this.checkedKeys)
            const _this = this;
            this.$confirm('是否确认删除名称为"' + row.name + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                const index = _this.menuList.findIndex( e => e.id === row.id)
                _this.menuList.splice(index,1)
                _this.checkedKeys = _this.menuList.map( e => e.id)
                console.log(_this.checkedKeys);
                _this.menuList = _this.menuList
            })
        }
    }
}
</script>

<style scoped lang='scss'>
.execution {
    .basic-container {
        padding-top: 10px;
    }
}
</style>